<template>
  <w-dialog :border="false" closeFree width="80vw" @ok="selectOk" @cancel="close" :title="title" v-model="visible">
    <div class="picker">
      <div class="candidate" v-loading="loading">
        <el-row :gutter="20">
          <!--公司数据-->
          <el-col :span="8" :xs="24">
            <div class="head-container">
              <el-select
                v-if="isLazy"
                v-model="selectedRemoteOrg"
                filterable
                remote
                reserve-keyword
                :loading="remoteLoading"
                placeholder="请输入机构名称进行过滤"
                :remote-method="remoteSearchOrgList"
                style="width: 240px;margin-bottom: 20px"
                clearable
              >
                <el-option v-for="item in remoteOrgList" :key="item.key" :label="item.name" :value="item">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; margin-left: 20px; color: var(--el-text-color-secondary); font-size: 13px;">{{ item.params.parentName }}</span>
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model="deptName"
                placeholder="请输入机构名称"
                clearable
                size="default"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="treeBox">
              <el-tree
                v-if="isLazy"
                node-key="id"
                :data="orgOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                lazy
                :load="lazyLoad"
                ref="tree"
                @node-click="handleNodeClick"
              >
                <template #default="{ node, data }">
                  <span class="tree-title">
                    <el-icon class="loading-icon" size="14" v-if="data.isLoading"><Loading /></el-icon>
                    <span v-if="data.params && data.params.type === 'C'">
                      <b>{{ node.label }}</b>
                      <el-tag type="info" size="default" class="ml10">公司</el-tag>
                    </span>
                    <span v-else>{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
              <el-tree
                v-else
                :data="orgOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              >
                <template #default="{ node, data }">
                  <span>
                    <span v-if="data.params.type === 'C'">
                      <b>{{ node.label }}</b>
                      <el-tag type="info" size="default" class="ml10">公司</el-tag>
                    </span>
                    <span v-else>{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-col>
          <!--用户数据-->
          <el-col :span="16" :xs="24">
            <el-form
              :model="queryParams"
              ref="queryForm"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
              @submit.prevent
            >
              <el-form-item label="用户名称" prop="userName">
                <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  size="default"
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleQuery" />
                <reset-button @click="resetQuery" />
              </el-form-item>
            </el-form>
            <el-table
              :row-key="getRowKey"
              v-loading="loading"
              :data="userList"
              @select="onSelect"
              @select-all="onSelectAll"
              ref="multipleTable"
              @row-click="handleCurrent"
            >
              <el-table-column
                v-if="!isRadio"
                type="selection"
                width="50"
                align="center"
              />
              <el-table-column
                label="用户名称"
                min-width="160"
                align="center"
                prop="userName"
                :show-overflow-tooltip="true"
              >
                <template #default="scope">
                  {{ scope.row.userName + '(' + scope.row.loginName + ')' }}
                </template>
              </el-table-column>
              <el-table-column
                label="公司/部门"
                min-width="180"
                align="center"
                prop="companyName"
                :show-overflow-tooltip="true"
              >
                <template #default="scope">
                  {{ (scope.row.companyName || '-') + ' / ' + (scope.row.deptName || '-') }}
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-show="total > 0"
              small
              layout="prev, pager, next"
              :total="total"
              :current-page="queryParams.pageNum"
              @current-change="handleCurrentChange"
            />
          </el-col>
        </el-row>
      </div>
      <div class="selected">
        <div class="count">
          <span>已选 {{ select.length }} 项</span>
          <span @click="clearSelected">清空</span>
        </div>
        <div class="org-items" style="height: 350px">
          <el-empty
            :image-size="100"
            description="请点击左侧列表选择数据"
            v-show="select.length === 0"
          />
          <div v-for="(org, index) in select" :key="index" class="org-item">
            <div>
              <el-icon><FolderOpened /></el-icon>
              <!-- <i class="el-icon-folder-opened"></i> -->
              <span style="position: static" class="name">{{
                  org.userName + '(' + org.loginName + ')'
                }}</span>
            </div>
            <el-icon class="el-icon el-icon-close" @click="noSelected(org, index)"
            ><Close/></el-icon>
            <!-- <i class="el-icon-close" @click="noSelected(org,index)"></i> -->
          </div>
        </div>
      </div>
    </div>
  </w-dialog>
</template>

<script>
import 'vue3-treeselect/dist/vue3-treeselect.css'
import { orgTreeList, listPage, orgTreeFirstListByParentId, remoteSearchOrgList } from './orgPicker'
import { debounceWrapper } from '@/utils/zmids'

export default {
  name: 'OrgPicker',
  components: {},
  props: {
    title: {
      default: '请选择',
      type: String
    },
    type: {
      default: 'org', //org选择部门/人员  user-选人  dept-选部门 role-选角色
      type: String
    },
    isRadio: {
      default: false,
      type: Boolean
    },
    selected: {
      default: () => {
        return []
      },
      type: Array
    },
    isLazy: {
      default: false,
      type: Boolean
    },
    rootCompanyId: {
      default: 'root',
      type: String
    }
  },
  emits: ['ok'],
  data() {
    return {
      visible: false,
      checkAll: false,
      searchUsers: [],
      nodes: [],
      select: [],
      search: '',
      deptStack: [],

      // 遮罩层
      loading: false,
      // 远程加载loading
      remoteLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 公司部门组织树选项
      orgOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        companyId: undefined,
        deptId: undefined
      },
      // 远程搜索机构列表
      remoteOrgList: [],
      // 被选中的远程搜索机构
      selectedRemoteOrg: undefined
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      if (!this.isLazy){
        this.$refs.tree.filter(val)
      }
    },
    selectedRemoteOrg(val) {
      if (val){
        this.remoteSearchOrgTreeList(val)
      }else{
        orgTreeFirstListByParentId(this.rootCompanyId,this.rootCompanyId,'C').then((response)=>{
          this.orgOptions = response.data;
          this.queryParams.companyId = undefined
          this.queryParams.deptId = undefined
          this.getList1()
        });
      }
    }
  },
  created() {
    this.getList1()
    if (!this.isLazy){
      this.getTreeselect()
    }
  },
  methods: {
    getRowKey(row) {
      return row.userId
    },
    async show() {
      // await this.getList1();
      // this.getTreeselect();
      this.visible = true
      this.init()
    },
    noSelected(org, index) {
      this.select.forEach((item) => {
        if (item.userId == org.userId) {
          this.$refs.multipleTable.toggleRowSelection(item, false)
        }
      })
      this.select.splice(index, 1)
    },
    recover() {
      this.$refs.multipleTable.clearSelection()
      this.select = []
    },
    selectOk() {
      this.$emit(
        'ok',
        Object.assign(
          [],
          this.select.map((v) => {
            v.avatar = undefined
            return v
          })
        )
      )
      this.visible = false
      this.recover()
    },
    clearSelected() {
      this.$confirm('您确定要清空已选中的项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.recover()
      })
    },
    close() {
      this.selectedRemoteOrg = undefined
      this.queryParams.userName = undefined
      this.$emit('close')
      this.recover()
    },
    init() {
      this.checkAll = false
      this.deptStack = []
      this.nodes = []
      this.select = Object.assign([], this.selected)
      console.log(this.select, this.userList, 'ite.userId')
      this.userList = this.userList ? this.userList : []
      this.$nextTick(() => {
        this.select.forEach((ite) => {
          this.userList.forEach((item) => {
            if (item.userId == ite.userId) {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
        })
      })
    },

    /** 查询用户列表 */
    getList1() {
      this.loading = true
      return listPage(
        this.addDateRange(this.queryParams, ['updateTimeStart', 'updateTimeEnd'], this.dateRange)
      ).then((response) => {
        this.userList = response.data.list
        this.$nextTick(() => {
          // 比较select列表，进行多选回显
          this.userList.forEach((item) => {
            this.select.forEach((ite) => {
              if (item.userId === ite.userId) {
                this.$refs.multipleTable.toggleRowSelection(item, true)
              }
            })
          })
        })
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      //仅查询正常的机构
      orgTreeList().then((response) => {
        console.log(response.data, 'response.data;')
        this.orgOptions = response.data
      })
    },
    /** 远程搜索公司部门 */
    remoteSearchOrgList(value) {
      if (value) {
        this.remoteLoading = true;
        setTimeout(() => {
          remoteSearchOrgList(value).then(res => {
            this.remoteOrgList = res.data;
            this.remoteLoading = false;
          });
        }, 200);
      } else {
        this.remoteOrgList = [];
        this.selectedRemoteOrg = undefined;
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick: debounceWrapper(function (data) {
      this.queryParams.companyId = undefined
      this.queryParams.deptId = undefined
      if (data && data.params) {
        if (data.params['type'] === 'C') {
          this.queryParams.companyId = data.params['companyId']
        } else if (data.params['type'] === 'D') {
          this.queryParams.companyId = data.params['companyId']
          this.queryParams.deptId = data.params['deptId']
        }
      }
      this.getList1()
    }),
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        companyId: undefined,
        deptId: undefined,
        loginName: undefined,
        userName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remark: undefined,
        postIds: [],
        roleIds: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery: debounceWrapper(function () {
      this.queryParams.page = 1
      this.getList1()
    }),
    /** 重置按钮操作 */
    resetQuery: debounceWrapper(function () {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.companyId = undefined
      this.queryParams.deptId = undefined
      this.queryParams.userName = undefined
      this.deptName = ''
      this.handleQuery()
    }),
    // 多选操作
    onSelect(selection, row){
      if (!this.isRadio) {
        const {userId} = row
        const index = this.select.findIndex(i => i.userId === userId)
        // 如果已经包含该项 说明本次是取消勾选
        if (index > -1) {
          this.select.splice(index, 1)
        } else {
          // 否则，将已勾选的push进去
          this.select.push(row)
        }
      }
    },
    // 全选操作
    onSelectAll(selection) {
      if (!this.isRadio) {
        // 删除当前页面的数据
        const userIds = this.userList.map((item) => item.userId)
        this.select = this.select.filter(row => !userIds.includes(row.userId))
        // 重新添加当前页被选中的数据
        this.select.push(...selection)
        this.ids = selection.map((item) => item.userId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      }
    },
    handleCurrent(row) {
      //row就是行信息
      if (this.isRadio) {
        this.select = [row]
        this.ids = row.roleId
        // this.$refs.multipleTable.toggleRowSelection(row) // 传入行信息，使得该行复选框打上勾
      }
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.queryParams.pageSize = 10
      this.getList1()
    },
    lazyLoad(node, resolve) {
      if (node.level === 0) {
        return orgTreeFirstListByParentId(this.rootCompanyId,this.rootCompanyId,'C').then((response)=>{
          resolve(response.data)
        })
      }
      const { params } = node.data
      if(params.type == 'C'){
        return orgTreeFirstListByParentId(params.companyId, this.rootCompanyId, params.type).then((response) => {
          resolve(response.data)
        })
      }else if(params.type == 'D'){
        return orgTreeFirstListByParentId(params.deptId, this.rootCompanyId, params.type).then((response) => {
          resolve(response.data)
        })
      }
    },
    remoteSearchOrgTreeList(data) {
      if (data){
        const params = data.params;
        if(params.type == 'C'){
          return orgTreeFirstListByParentId(params.companyId, this.rootCompanyId, params.type).then((response) => {
            this.orgOptions = response.data;
          })
        }else if(params.type == 'D'){
          return orgTreeFirstListByParentId(params.deptId, this.rootCompanyId, params.type).then((response) => {
            this.orgOptions = response.data;
          })
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.treeBox {
  height: 300px;
  overflow: auto;
}
.candidate,
.selected {
  position: absolute;
  display: inline-block;
  height: 400px;
  border: 1px solid #e8e8e8;
}

.picker {
  height: 402px;
  position: relative;
  text-align: left;
  .candidate {
    left: 0;
    top: 0;
    width: 70%;

    & > div:first-child {
      padding: 5px 10px;
    }
  }

  .selected {
    right: 0;
    top: 0;
    width: 30%;
  }

  .org-items {
    overflow-y: auto;
    height: 310px;

    .el-icon-close {
      position: absolute;
      right: 5px;
      cursor: pointer;
      font-size: larger;
    }

    .org-role-item {
      display: flex;
      align-items: center;
      padding: 10px 5px;
    }

    :deep(.org-user-item) {
      display: flex;
      align-items: center;
      padding: 5px;

      & > div {
        display: inline-block;
      }

      .avatar {
        width: 35px;
        text-align: center;
        line-height: 35px;
        background: #1890ff;
        color: white;
        border-radius: 50%;
      }
    }

    :deep(.org-item) {
      margin: 0 5px;
      border-radius: 5px;
      padding: 10px 5px;
      display: flex;
      .el-checkbox {
        margin-right: 10px;
      }

      .name {
        margin-left: 5px;
      }

      &:hover {
        background: #f1f1f1;
      }
    }
  }
}

.selected {
  border-left: none;
  .count {
    width: 100%;
    padding: 10px;
    display: inline-block;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 5px;
    & > span:nth-child(2) {
      float: right;
      color: #c75450;
      cursor: pointer;
    }
  }
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

.disabled {
  cursor: not-allowed !important;
  color: #8c8c8c !important;
}

::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #efefef;
}

:deep(.el-table) {
  height: calc(400px - 100px);
}
:deep(.el-table__body-wrapper) {
  height: calc(100% - 50px);
  overflow-y: auto;
  overflow-x: hidden;
}
:deep(.el-pagination) {
  float: right;
}
</style>
